package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @Author : sunjun
 * @email : sunjun0207@163.com
 * @create 2019/11/13 13:21
 */

/*
操作短信验证码
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    //注入redis缓存
    @Autowired
    private JedisPool jedisPool;


    /*
    移动端-->手机快速登录时发送验证码
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        //获取验证码工具类validateCodeUtils自动生成的验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        try {
            //测试代码
            System.out.println("输入的手机号为:"+ telephone+ "生成的验证码为:" + code.toString());
            //调用发送短信工具类SMSUtils发送短信
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());

            //发送验证码成功,将验证码存入Redis缓存中
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN,300,code.toString());
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //验证码发送失败
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }



    /*
    移动端-->短信服务发送验证码保存到Redis
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //调用验证码工具类生成4位验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        try {
            //用于测试
            //打印日志消息,生成的验证码code
            System.out.println("生成的验证码:" + code.toString());
            System.out.println("输入的手机号0为:" + telephone);
            //调用短信工具类发送短信验证码
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
            //将生成的验证码存入Redis缓存中
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER,300,code.toString());
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //验证码发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }
}
